"""
Web
"""

import streamlit as st
import tempfile
import os
from pathlib import Path
from src.core.video_processor import VideoProcessor
from src.core.utils import format_file_size, format_duration

class FileUploader:
    """"""
    
    def __init__(self):
        self.video_processor = VideoProcessor()
    
    def render(self):
        """"""
        st.header(" ")
        
        uploaded_file = st.file_uploader(
            "",
            type=['mp4', 'avi', 'mkv', 'mov', 'wmv', 'flv', 'webm', 'm4v', 
                  'mp3', 'wav', 'flac', 'aac', 'ogg', 'm4a'],
            help=""
        )
        
        if uploaded_file is not None:
            return self._process_uploaded_file(uploaded_file)
        
        return None
    
    def _process_uploaded_file(self, uploaded_file):
        """"""
        # 
        file_size = len(uploaded_file.getvalue())
        st.success(f" : {uploaded_file.name} ({format_file_size(file_size)})")
        
        # 
        with tempfile.NamedTemporaryFile(delete=False, suffix=Path(uploaded_file.name).suffix) as tmp_file:
            tmp_file.write(uploaded_file.getvalue())
            temp_path = tmp_file.name
        
        # 
        try:
            video_info = self.video_processor.get_video_info(temp_path)
            if video_info:
                st.session_state.video_info = video_info
                st.session_state.video_info['temp_path'] = temp_path
                st.session_state.video_info['original_name'] = uploaded_file.name
                self._display_video_info(video_info)
                return temp_path
        except Exception as e:
            st.error(f" : {e}")
            os.unlink(temp_path)
        
        return None
    
    def _display_video_info(self, video_info):
        """"""
        st.subheader(" ")
        
        col1, col2, col3 = st.columns(3)
        
        with col1:
            st.metric("⏱ ", format_duration(video_info['duration']))
            st.metric(" ", format_file_size(video_info['file_size']))
        
        with col2:
            if 'width' in video_info:
                st.metric(" ", f"{video_info['width']}×{video_info['height']}")
                st.metric(" ", f"{video_info['fps']:.1f} fps")
        
        with col3:
            st.metric(" ", video_info['format_name'])
            if 'sample_rate' in video_info:
                st.metric(" ", f"{video_info['sample_rate']}Hz")